<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/10
 * Time: 17:26
 */

namespace App\Services;

use App\Models\Task;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;

class TaskService extends BaseService
{
    protected $modelClass = Task::class;

    /**
     * 添加
     * @param $postData
     * @return bool|string
     * @throws \Exception
     */
    public function add($postData)
    {
        return $this->saveData($postData);
    }

    /**
     * 编辑
     * @param $id
     * @param $postData
     * @return mixed
     * @throws \Exception
     */
    public function edit($id, $postData)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->update(filter_null($postData))) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 详情
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function detail1($id)
    {
        try {
            $obj = $this->model
                ->where('id', $id)
                ->with(['attach', 'finishAttach', 'assignUser', 'log'])
                ->first();

            if (!$obj) {
                throw new \Exception('未找到！');
            }

            return $obj;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 删除
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function remove($id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process == '进行中') {
                throw new \Exception('不能删除进行中的任务！');
            }

            return $obj->update(['is_enable' => 0]);
        } catch (\Exception $e) {
            throw new \Exception('删除失败！');
        }
    }

    /**
     * @param $id
     * @return mixed
     * @throws \Exception
     */
    public function cancel($id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '待开始') {
                throw new \Exception('只能取消待开始状态的任务！');
            }

            return $obj->update([
                'process' => '已取消',
                'user_id' => 0,
                'username' => '',
                'assigned_at' => null,
            ]);
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @param $id
     * @param $user_id
     * @return bool|mixed
     * @throws \Exception
     */
    public function start($id, $user_id)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '待开始') {
                throw new \Exception('只能开始待开始的任务！');
            }

            if ($obj->user_id != $user_id) {
                throw new \Exception('只能开始自己的任务！');
            }

            if ($obj->update([
                'process' => '进行中',
            ])) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @param $id
     * @param $user_id
     * @return bool|mixed
     * @throws \Exception
     */
    public function finish($id, $user_id, $postData)
    {
        try {
            $obj = $this->findByIdOrFail($id);
            if ($obj->process != '进行中') {
                throw new \Exception('只能完成进行中的任务！');
            }

            if ($obj->user_id != $user_id) {
                throw new \Exception('只能完成自己的任务！');
            }

            if ($obj->update([
                'process' => '已完成',
                'finish_attach_id' => $postData['finish_attach_id'],
                'finished_at' => date('Y-m-d H:i:s')
            ])) {
                return $obj;
            }

            return false;
        } catch (\Exception $e) {
            throw new \Exception('操作失败！');
        }
    }

    /**
     * @desc 列表
     * @param array $search
     * @param int $per_page
     * @return array
     */
    public function getList($search=[], $per_page=20)
    {
        $res = $this->model->with(['attach', 'finishAttach', 'assignUser', 'log']);

        if (!empty($search['user_id'])) {
            $res = $res->where('user_id', $search['user_id']);
        }

        if (!empty($search['filename'])) {
            $res = $res->where('filename', 'like', "%{$search['filename']}%");
        }

        if (!empty($search['username'])) {
            $res = $res->where('username', 'like', "%{$search['username']}%");
        }

        if (!empty($search['importance'])) {
            $res = $res->where('importance', $search['importance']);
        }

        if (!empty($search['process'])) {
            $res = $res->where('process', $search['process']);
        }

        if (!empty($search['assignDate'])) {
            $res = $res->whereBetween('assigned_at', $search['assignDate']);
        }

        if (!empty($search['type'])) {
            $res = $res->whereHas('attach', function($query)use($search){
                $query->where('suffix', $search['type']);
            });
        }

        if (!empty($search['sort'])) {
            if ($search['sort'] == '-id') {
                $res = $res->orderBy('id', 'desc');
            } else {
                $res = $res->orderBy('id', 'asc');
            }
        }

        return $this->get_paginate($res->paginate($per_page, ['*']));
    }

    public function info()
    {
        $res = [
            'all' => 0,
            'finish' => 0,
            'unAssign'=> 0,
            'processing' => 0,
        ];

        $obj = $this->getAll(['process']);
        foreach ($obj as $o) {
            if ($o->process == '已完成') {
                $res['finish'] ++;
            }
            if ($o->process == '未指派') {
                $res['unAssign'] ++;
            }
            if ($o->process == '进行中') {
                $res['processing'] ++;
            }

            $res['all'] ++;
        }

        return $res;
    }

    public function grid()
    {
        $grid = new Grid(new Task);
        $grid->quickSearch('name');
        $grid->column('id', __('ID'))->sortable();
        $grid->column('name', __('任务名称'))->filter('like');
        $grid->column('start_at', __('开始时间'));
        $grid->column('end_at', __('结束时间'));
        $grid->column('process', __('状态'))->filter([
            '待开始','已完成','进行中'
        ]);
        $grid->column('qr_asset_id', __('二维码'));
        $grid->column('question_num', __('问题数量'));
        $grid->column('sign_in', __('签到?'))->display(function ($column) {
            return $column ? '是' : '否';
        });
        $grid->column('sign_out', __('签退?'))->display(function ($column) {
            return $column ? '是' : '否';
        });
        $grid->column('created_at', __('创建时间'));
        $grid->filter(function($filter){ // 在这里添加字段过滤器
            $filter->like('name', '名称');
        });

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    public function detail($id)
    {
        $show = new Show(Task::findOrFail($id));

        $show->field('id', __('ID'));
        $show->field('name', __('任务名称'));
        $show->field('start_at', __('开始时间'));
        $show->field('end_at', __('结束时间'));
        $show->field('process', __('状态'));
        $show->field('qr_asset_id', __('二维码'));
        $show->field('question_num', __('问题数量'));
        $show->field('sign_in', __('签到?'))->as(function ($column) {
            return $column ? '是' : '否';
        });
        $show->field('sign_out', __('签退?'))->as(function ($column) {
            return $column ? '是' : '否';
        });
        $show->field('created_at', __('创建时间'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    public function form()
    {
        $states = [
            'on'  => ['value' => 1, 'text' => '打开', 'color' => 'success'],
            'off' => ['value' => 0, 'text' => '关闭', 'color' => 'danger'],
        ];
        $form = new Form(new Task);

        $form->text('name', __('任务名称'))->rules('required');
        $form->datetime('start_at', __('开始时间'))->rules('required');
        $form->datetime('end_at', __('结束时间'));
        $form->switch('sign_in', __('签到'))->states($states);
        $form->switch('sign_out', __('签退'))->states($states);
        $form->saved(function (Form $form) {
            // 返回一个简单response
            return redirect('/manager/tasks');
        });

        return $form;
    }

}